<template>
  <view class="page">
    <Header> </Header>
    <view class="main_container">
      <view class="main_content">
        <Breadcrumb :text="'个人评测-团灭音标'"> </Breadcrumb>
        <RouterTabs :list="routerList" :current="4"> </RouterTabs>
        <view class="content">
          <view class="tabs">
            <u-tabs-swiper
              ref="uTabs"
              :list="list"
              :current="current"
              @change="tabsChange"
              :is-scroll="false"
              swiperWidth="750"
              bg-color="transparent"
              inactive-color="#dddddd"
              active-color="#333333"
              :bar-style="styleObject"
              bar-width="134"
              bar-height="80"
            ></u-tabs-swiper>
          </view>
          <view class="vocabulary">
            <view class="word">
              <view class="word_content">
                {{ vocabularyWord.word }}
              </view>
              <view class="word_pronunciation">
                {{ vocabularyWord.wordSoundmark }}
              </view>
            </view>
            <view class="notes">
              <view class="notes_content">
                <view class="notes_title"> 释义： </view>
                <view class="notes_text">
                  {{ vocabularyWord.wordParaphrase }}
                </view>
              </view>
              <view class="notes_content">
                <view class="notes_title"> 例句： </view>
                <view class="notes_text">
                  {{ vocabularyWord.wordExampleSentence }}<br />
                  {{ vocabularyWord.wordSentenceChinese }}
                </view>
              </view>
              <view class="notes_line"></view>
              <view class="notes_video" @click="playVideo()">
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/vocabulary_video.png"
                  mode="widthFiX"
                ></image>
              </view>
            </view>
            <view class="noop" v-if="!isRecord"></view>
            <view class="record" v-else-if="!isSuspend">
              <view class="record_time">
                正在录音{{ minuteNumber }}:{{ secondNumber }}
              </view>
              <RecordShape></RecordShape>
            </view>
            <view class="load" v-else-if="isSuspend && !isHandle">
              <u-loading mode="flower" size="96"></u-loading>
            </view>
            <view class="result" v-else-if="isSuspend && isHandle">
              <view class="info active" v-if="isPass">
                <view class="info_score">
                  <text>{{ score }}</text>
                  <text>分</text>
                </view>
                <view class="info_button">
                  <text>过关</text>
                </view>
              </view>
              <view class="info" v-else>
                <view class="info_score">
                  <text>{{ score }}</text>
                  <text>分</text>
                </view>
                <view class="info_button">
                  <text>未过关</text>
                </view>
              </view>
              <view class="phoneme">
                <view class="phoneme_title">
                  <text>标准发音</text>
                  <text>音素匹配</text>
                </view>
                <view class="phoneme_container">
                  <view
                    class="phoneme_content"
                    v-for="(item, index) in syllArray"
                    :key="index"
                  >
                    <text class="active">{{ item.content }}</text>
                    <text>{{ item.score }}</text>
                  </view>
                </view>
              </view>
            </view>
            <u-popup
              v-model="show"
              :zoom="false"
              mode="center"
              width="640rpx"
              height="360rpx"
              @click="show = false"
            >
              <view class="video">
                <video :src="videoUrl" controls object-fit="fill"></video>
              </view>
            </u-popup>
          </view>
          <view class="icon">
            <view class="icon_container">
              <view
                class="button_content again"
                @click="practiceAgain()"
                v-if="!isPass && showAnswer"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/vocabulary_again.png"
                  mode="widthFix"
                  style="width: 180rpx"
                ></image>
              </view>
              <view class="icon_content">
                <view class="icon_iamge" @click="playAudio()">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/sound.png"
                    mode="widthFix"
                    style="width: 74rpx"
                  ></image>
                </view>
                <view class="icon_text"> 听声音 </view>
              </view>
              <view class="icon_content" v-if="!isRecord" @click="record()">
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/voice.png"
                    mode="widthFix"
                    style="width: 52rpx"
                  ></image>
                </view>
                <view class="icon_text"> 开始录音 </view>
              </view>
              <view
                class="icon_content"
                v-else-if="!isSuspend"
                @click="endRecord()"
              >
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/suspend.png"
                    mode="widthFix"
                    style="width: 56rpx"
                  ></image>
                </view>
                <view class="icon_text"> 结束录音 </view>
              </view>
              <view class="icon_content" v-else-if="isSuspend && !isHandle">
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/wait.png"
                    mode="widthFix"
                    style="width: 63rpx"
                  ></image>
                </view>
                <view class="icon_text"> 处理中 </view>
              </view>
              <view
                class="icon_content"
                v-else-if="isSuspend && isHandle"
                @click="playVoice()"
              >
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/play.png"
                    mode="widthFix"
                    style="width: 43rpx"
                  ></image>
                </view>
                <view class="icon_text"> 我的录音 </view>
              </view>
              <view
                class="button_content next"
                @click="nextQuestion()"
                v-if="isPass && showAnswer"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/vocabulary_next.png"
                  mode="widthFix"
                  style="width: 140rpx"
                ></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>

<script>
import { findHitProgress, saveHitProgress } from "@/api/spelling";
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
import dictList from "@/libs/PronunciationDict";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
export default {
  components: {},
  data() {
    return {
      routerList: [
        {
          name: "练习字母",
          url: "`pages/spelling/letter",
        },
        {
          name: "浅学音标",
          url: "`pages/spelling/soundmarkShallow",
        },
        {
          name: "拼读训练",
          url: "`pages/spelling/spellingTraining",
        },
        {
          name: "团灭音标",
          url: "`pages/spelling/soundmarkAce",
        },
        {
          name: "暴击词汇",
          url: "`pages/spelling/vocabulary",
        },
      ],
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      list: [
        {
          name: "简单词汇",
        },
        {
          name: "中级词汇",
        },
        {
          name: "高级词汇",
        },
      ],
      current: 0, // tabs组件的current值，表示当前活动的tab选项
      styleObject: {
        background:
          "url('https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/tabs_bg.png') center/100% 100% no-repeat scroll",
        borderRadius: 0,
      },
      vocabularyWord: {},
      videoUrl: null,
      syllArray: [],
      timerId: null,
      second: 0,
      minute: 0,
      secondNumber: "00",
      minuteNumber: "00",
      isRecord: false,
      isSuspend: false,
      isHandle: false,
      isRejected: "false",
      score: 0,
      isPass: false,
      showAnswer: false,
      isShowPopup: false,
      isCanClick: true,
      show: false,
      showTips: false,
      tipsContent: "请不要乱读哦~",
    };
  },
  watch: {
    type() {
      this.initData();
      this.init();
    },
  },
  computed: {
    type() {
      if (this.current === 0) {
        return "1";
      } else if (this.current === 1) {
        return "2";
      } else if (this.current === 2) {
        return "3";
      }
    },
  },
  onLoad() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
    this.init();
  },
  methods: {
    init() {
      let params = {
        course: this.type,
      };
      findHitProgress(params).then((res) => {
        this.wordNum = res.data.wordNum;
        this.vocabularyWord = res.data.word;
      });
    },
    initData() {
      this.isRecord = false;
      this.isSuspend = false;
      this.isHandle = false;
      this.showAnswer = false;
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.time();
      this.isRecord = true;
    },
    endRecord() {
      this.isSuspend = true;
      recorderManager.stop();
      clearInterval(this.timerId);
      this.second = 0;
      this.minute = 0;
    },
    playVoice() {
      if (!englishAudioContext.paused) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, { wordText: this.vocabularyWord.word }).then(
        (res) => {
          let xml = res.data;
          let grade = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
          });
          if (grade) {
            let read_chapter =
              grade.xml_result.read_sentence.rec_paper.read_chapter;
            this.getSyllData(read_chapter);
            this.isRejected = read_chapter.is_rejected;
            if (this.isRejected === "true") {
              this.showTips = true;
              setTimeout(() => {
                this.showTips = false;
              }, 2000);
            }
            this.score = Number(read_chapter.total_score).toFixed(2);
            this.isPass = this.score >= 60 ? true : false;
            this.isHandle = true;
            this.showAnswer = true;
          }
        }
      );
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    playAudio() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.vocabularyWord.wordAudio;
      englishAudioContext.play();
    },
    playVideo() {
      this.videoUrl = this.vocabularyWord.wordVideo;
      this.show = true;
    },
    getSyllData(result) {
      let syllArray = [];
      let sentence = result.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.content === "fil" || item.content === "sil") return;
          let anSyllArray = [];
          if (!Array.isArray(item.syll)) {
            anSyllArray.push(item.syll);
          } else {
            anSyllArray = item.syll;
          }
          anSyllArray.forEach((item) => {
            let syll_score = Number(item.syll_score).toFixed(2);
            const nonStandard = item.content;
            const splitResult = nonStandard.split(" "); // 分割成 ["eh", "m"]
            const standardResult = splitResult
              .map((phoneme) => {
                const found = dictList.find(
                  (item) => item.nonstandard === phoneme
                );

                return found ? found.standard : phoneme; // 如果找到映射则替换，否则保持原样
              })
              .join(" ");
            let syll_content = standardResult;
            syllArray.push({
              content: syll_content,
              score: syll_score,
            });
          });
        });
      });
      this.syllArray = syllArray;
    },
    practiceAgain() {
      this.initData();
    },
    nextQuestion() {
      this.initData();
      let params = {
        course: this.type,
        wordNum: this.wordNum,
      };
      saveHitProgress(params).then((res) => {
        if (!res.data.endFlag) {
          this.wordNum = res.data.wordNum;
          this.vocabularyWord = res.data.word;
        } else {
          uni.showModal({
            title: "温馨提示",
            content: "单词已学完，您下次将从头开始学习",
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                uni.navigateBack({
                  data: 1,
                });
              }
            },
          });
        }
      });
    },
    tabsChange(index) {
      this.current = index;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./vocabulary";
</style>
